package register

import (
	"fmt"
	"gitee.com/Hu-Lyndon/distill-resk/infra"
	"gitee.com/Hu-Lyndon/distill-resk/infra/base"
	"gitee.com/Hu-Lyndon/distill-resk/infra/utils"
	"gitee.com/Hu-Lyndon/distill-resk/infra/web"
	consulapi "github.com/hashicorp/consul/api"
	"github.com/kataras/iris"
	"github.com/segmentio/ksuid"
)

var consulClient *consulapi.Client

func ConsulClient() *consulapi.Client {
	utils.Check(consulClient)
	return consulClient
}

type ConsulStarter struct {
	infra.BaseStarter
	//client *consulapi.Client
}

func (e *ConsulStarter) Init(ctx infra.StarterContext) {
	config := consulapi.DefaultConfig()
	client, err := consulapi.NewClient(config)
	if err != nil {
		panic(err)
	}
	consulClient = client
}

func (e *ConsulStarter) Start(ctx infra.StarterContext) {
	var err error
	props := base.Props()

	web.IrisMainParty().Get("/actuator/health", func(context iris.Context) {
		context.JSON(iris.Map{"status": "UP"})
	})

	registration := new(consulapi.AgentServiceRegistration)
	registration.ID = ksuid.New().Next().String() //fmt.Sprintf("%s-%s-%d", c.Spring.Application.Name, ip, c.Server.Port)
	registration.Name = props.GetDefault("app.name", "resk")
	registration.Port = props.GetIntDefault("app.server.port", 8080)
	registration.Tags = []string{}
	//var ip string
	//activeIPs, err := utils.GetActiveIps()
	//if err != nil {
	//	ip = "localhost"
	//} else {
	//	ip = activeIPs[0]
	//}
	registration.Address = "localhost"
	registration.Check = &consulapi.AgentServiceCheck{
		HTTP:                           fmt.Sprintf("http://%s:%d%s", registration.Address, registration.Port, "/actuator/health"),
		Timeout:                        "60s",
		Interval:                       "3s",
		DeregisterCriticalServiceAfter: "30s",
	}

	fmt.Println(fmt.Sprintf("http://%s:%d%s", registration.Address, registration.Port, "/actuator/health"))

	err = consulClient.Agent().ServiceRegister(registration)

	if err != nil {
		fmt.Errorf("register server error : ", err)
	}
}
